<?php


namespace api\controllers;


use api\components\BaseController;
use common\cache\DictCache;
use common\helpers\commonApi;
use common\helpers\PageApi;
use common\helpers\QiniuApi;
use common\models\Address;
use common\models\Order;
use common\models\OrderComment;
use common\models\OrderGoods;
use common\models\OrderLog;
use common\models\OrderRefund;
use common\models\System;
use common\models\User;
use Yii;

class OrderController extends BaseController
{
    /**
     * 订单列表
     * @return array
     */
    public function actionList()
    {
        $userid = self::$userid;
        $get = Yii::$app->request->get();
        $status = (int)$get['status']??0;
        $page = (int)$get['page']??1;
        $query = Order::find()
            ->with(['goods'])
            ->where(['userid'=>$userid])
            ->orderBy(['create_time'=>SORT_DESC]);
        $orderTable = Order::tableName();
        switch ($status){
            case 1://待支付
                $query->andWhere([$orderTable.'.order_status'=>0,$orderTable.'.pay_status'=>0]);
                break;
            case 2://待发货
                $query->andWhere([$orderTable.'.order_status'=>1]);
                break;
            case 3://待收货
                $query->andWhere([$orderTable.'.order_status'=>2]);
                break;
            case 4://待评价
                $query->andWhere([$orderTable.'.order_status'=>3,$orderTable.'.is_comment'=>0]);
                break;
        }
        $data = PageApi::apiPage($query,$page,1);
        $arr = [];
        foreach ($data['data'] as $datum){
            $goodArr = [];
            foreach ($datum['goods'] as $good){
                $good_info = json_decode($good['good_info'],true);
                $goodArr[] = [
                    'good_price'=>$good['good_price'],
                    'good_num'=>$good['good_num'],
                    'good_name'=>$good['good_name'],
                    'spec_name'=>$good['spec_name'],
                    'main_img'=>commonApi::getDomain($good_info['main_img']),
                    'order_good_id'=>$good['id'],
                    'is_comment'=>$good['is_comment']??0,
                ];
            }

            $arr[] = [
                'good'=>$goodArr,
                'pay_amount'=>$datum['pay_amount'],
                'total_num'=>$datum['total_num'],
                'order_sn'=>$datum['order_sn'],
            ];
        }
        $data['data'] = $arr;
        return commonApi::message('成功',true,$data);
    }

    /**
     * 详情
     * @return array
     */
    public function actionDetails()
    {
        $order_sn = Yii::$app->request->get('order_sn','');
        if (!$order_sn){
            return commonApi::message('请选择要查看订单号',false);
        }
        $userid = self::$userid;
        $order = Order::find()->where(['order_sn'=>$order_sn,'userid'=>$userid])->one();
        if (!$order){
            return commonApi::message('订单号错误！',false);
        }
        $ordergoods = OrderGoods::find()->where(['order_id'=>$order->id])->asArray()->all();
        $spec = [];
        foreach ($ordergoods as $og){
            $good_info = json_decode($og['good_info'],true);
            $spec[] = [
                'main_img'=>commonApi::getDomain($good_info['main_img']),
                'price'=>$og['good_price'],
                'num'=>$og['good_num'],
                'spec_name'=>$og['spec_name'],
                'good_name'=>$og['good_name'],
                'order_good_id'=>$og['id'],
                'is_comment'=>$og['is_comment']??0,
            ];
        }

        $data = [
            'consignee'=>$order->consignee,
            'mobile'=>$order->mobile,
            'province'=>$order->province,
            'city'=>$order->city,
            'district'=>$order->district,
            'address'=>$order->address,
            'spec'=>$spec,
            'total_amount'=>$order->total_amount,
            'pay_amount'=>$order->pay_amount,
            'discount_amount'=>$order->discount_amount,
            'freight'=>$order->freight,
            'express_sn'=>$order->express_sn??'',
            'express_type'=>$order->express_type??'',
        ];
        return commonApi::message('成功',true,$data);
    }

    /**
     * 修改地址
     * @return array
     */
    public function actionEditAddr()
    {
        $order_sn = Yii::$app->request->post('order_sn','');
        $address_id = Yii::$app->request->post('address_id','');
        if (!$order_sn){
            return commonApi::message('请选择要修改的订单号',false);
        }
        if (!$address_id){
            return commonApi::message('请选择地址',false);
        }
        $useris = self::$userid;
        $order = Order::find()->where(['order_sn'=>$order_sn,'userid'=>$useris])->one();
        if (!$order){
            return commonApi::message('订单号错误！',false);
        }
        if ($order->pay_status!==0||$order->order_status!==0){
            return commonApi::message('订单不支持修改地址',false);
        }
        $address = Address::find()->where(['id'=>$address_id,'userid'=>$useris])->one();
        if (!$address){
            return commonApi::message('地址不存在',false);
        }
        $order->consignee = $address->consignee;
        $order->province = $address->province;
        $order->city = $address->city;
        $order->district = $address->district;
        $order->address = $address->address;
        $order->mobile = $address->mobile;
        if ($order->save()!==false){
            OrderLog::addLog($useris,$order->id,'用户修改地址','用户修改地址',2);
            return commonApi::message('修改地址成功');
        }
        return commonApi::message('修改地址失败！',false);
    }

    /**
     * 继续支付
     * @return \api\components\B5Response|array|false
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function actionAgainPay()
    {
        $userid = self::$userid;
        $order_sn = Yii::$app->request->post('order_sn','');
        if (!$order_sn){
            return commonApi::message('请选择要继续支付的订单！',false);
        }
        $model = Order::find()->where(['userid'=>$userid,'order_sn'=>$order_sn])->one();
        if (!$model){
            return commonApi::message('该订单不存在！',false);
        }
        if ($model->pay_status!==0||$model->order_status!==0){
            return commonApi::message('该订单不支持继续支付！',false);
        }
        $party_order = Order::makePartyOrder();
        $model->party_order = $party_order;
        //生成支付数据
        $desc = '购买商品-'.$order_sn;
        $payData = Order::getPayresponse($model->pay_amount,$userid,$party_order,$desc);
        if ($payData['success']==true){
            OrderLog::addLog($userid,$model->id,'用户再次支付','用户再次支付',2);
            $model->save();
            return $this->returnJson()->b5success('下单成功',$payData['data']);
        }else{
            return $payData;
        }
    }

    /**
     * 确认收货
     * @return \api\components\B5Response|false
     */
    public function actionConfirmReceipt()
    {
        $userid = self::$userid;
        $order_sn = Yii::$app->request->post('order_sn','');
        if (!$order_sn){
            return commonApi::message('请选择要收货的订单',false);
        }
        $model = Order::find()->where(['userid'=>$userid,'order_sn'=>$order_sn])->one();
        if (!$model){
            return commonApi::message('该订单不存在',false);
        }
        if ($model->order_status!==2){
            return commonApi::message('该订单不支持收货',false);
        }
        $model->confirm_take_time = date('Y-m-d H:i:s');
        $model->order_status = 3;
        if ($model->save()){
            OrderLog::addLog($userid,$model->id,'用户确认收货','用户确认收货',2);
            return commonApi::message('收货成功');
        }
        return commonApi::message('收货失败',false);
    }

    /**
     * 评论
     * @return \api\components\B5Response|false
     */
    public function actionComment()
    {
        $params = Yii::$app->request->post();
        $userid = self::$userid;
        $order_sn = $params['order_sn']??'';
        $order_good_id = $params['order_good_id']??'';
        $logistics_star = $params['logistics_star']??'';
        $service_attitude = $params['service_attitude']??'';
        $content = $params['content']??'';
        $imgs = $params['imgs']??'';
        if (!$order_good_id){
            return commonApi::message('请选择要评论的订单商品',false);
        }
        if (!$order_sn){
            return commonApi::message('请选择订单',false);
        }
        if (!$logistics_star){
            return commonApi::message('请选择物流服务评分',false);
        }
        if (!$service_attitude){
            return commonApi::message('请选择服务态度评分',false);
        }
        if (!$content){
            return commonApi::message('请输入评论内容',false);
        }
        if (!$imgs){
            return commonApi::message('请选择图片',false);
        }
        $order = Order::find()->where(['order_sn'=>$order_sn,'userid'=>$userid])->one();
        if (!$order){
            return commonApi::message('该订单不存在',false);
        }
        if ($order->order_status!==3){
            return commonApi::message('订单还未完成，不能进行评论',false);
        }
        $ordergoods = OrderGoods::find()->where(['id'=>$order_good_id])->one();
        if (!$ordergoods){
            return commonApi::message('该订单商品不存在',false);
        }
        $count = OrderComment::find()
            ->where(['order_good_id'=>$order_good_id])
            ->count();
        $count = $count??0;
        if ($count>=1){
            return commonApi::message('已经评论',false);
        }
        $ordergoods->is_comment = 1;
        $system = System::getModel();
        $is_review = $system->order_evaluate;
        $imgsa = explode("*|*",$imgs);
        if (!$system->qiniu_ak||!$system->qiniu_sk||!$system->qiniu_bucket||!$system->qiniu_domain){
            return commonApi::message('请设置七牛云！',false);
        }
        $qiniu = new QiniuApi($system->qiniu_ak,$system->qiniu_sk,$system->qiniu_bucket,$system->qiniu_domain,'png');
        $imgArr = [];
        foreach ($imgsa as $img){
            $res = $qiniu->run($img);
            if (!$res['success']){
                $qiniu->delAll($imgArr);
                return commonApi::message('七牛云上传失败'.$res['msg'], false);
            }else{
                $imgArr[] = $res['data']['path'];
            }
        }
        $userInfo = User::find()->where(['id'=>$userid])->select(['info'])->scalar();
        $model = new OrderComment();
        $model->userid = $userid;
        $model->good_id = $ordergoods->good_id;
        $model->order_id = $order->id;
        $model->order_good_id = $order_good_id;
        $model->logistics_star = $logistics_star;
        $model->service_attitude = $service_attitude;
        $model->content = $content;
        $model->info = $userInfo;
        $model->imgs = implode(',',$imgArr);
        if ($is_review){
            $model->status = 0;
        }else{
            $model->status = 1;
            $model->review_time = date('Y-m-d H:i:s');
        }
        if ($model->save()){
            $ordergoods->save();
            $exists = OrderGoods::find()->where(['order_id'=>$order->id,'is_comment'=>0])->exists();
            if (!$exists){
                $order->is_comment = 1;
                $order->save();
            }
            $nu = $count+1;
            OrderLog::addLog($userid,$order->id,'用户第'.$nu.'次评论','用户第'.$nu.'次评论：'.$order_good_id,2);
            return $this->returnJson()->b5success('评论成功');
        }
        return $this->returnJson()->b5error('评论失败');
    }

    /**
     * 申请退款
     * @return \api\components\B5Response|false
     */
    public function actionRefund()
    {
        $userid = self::$userid;
        $params = Yii::$app->request->post();
        $order_sn = $params['order_sn']??'';
        $order_good_id = $params['order_good_id']??'';
        $refund_way = $params['refund_way']??'';//方式
        $cause = $params['cause']??'';//原因
        $imgs = $params['imgs']??'';//图片 *|*
        if (!$order_sn){
            return commonApi::message('请选择要退款的订单',false);
        }
        if (!$imgs){
            return commonApi::message('请上传图片',false);
        }
        $model = Order::find()->where(['userid'=>$userid,'order_sn'=>$order_sn])->one();
        if (!$model){
            return commonApi::message('该订单不存在',false);
        }
        if ($model->order_status==0){
            return commonApi::message('该订单不支持退款',false);
        }
        $ordergoods = OrderGoods::find()->where(['id'=>$order_good_id])->one();
        if (!$ordergoods){
            return commonApi::message('该订单商品不存在',false);
        }
        if ($ordergoods->refund_status!==0){
            $refund_status = DictCache::get('sys_order_good_refund_status');
            $msg = '该订单已经'.$refund_status[$ordergoods->refund_status].'请勿重复申请';
            return commonApi::message($msg,false);
        }
        $ordergoods->refund_status = 1;
        $data = [
            'userid'=>$userid,'order_id'=>$model->id,'order_good_id'=>$order_good_id,
            'refund_way'=>$refund_way,'amount'=>$ordergoods->total_pay_price,'cause'=>$cause
        ];
        $system = System::getModel();
        $imgsa = explode("*|*",$imgs);
        if (!$system->qiniu_ak||!$system->qiniu_sk||!$system->qiniu_bucket||!$system->qiniu_domain){
            return commonApi::message('请设置七牛云！',false);
        }
        $qiniu = new QiniuApi($system->qiniu_ak,$system->qiniu_sk,$system->qiniu_bucket,$system->qiniu_domain,'png');
        $imgArr = [];
        foreach ($imgsa as $img){
            $res = $qiniu->run($img);
            if (!$res['success']){
                $qiniu->delAll($imgArr);
                return commonApi::message('七牛云上传失败'.$res['msg'], false);
            }else{
                $imgArr[] = $res['data']['path'];
            }
        }

        $modelR = new OrderRefund();
        $modelR->load($data,'');
        $modelR->imgs = implode(',',$imgArr);
        $modelR->sn = OrderRefund::makeOrderid();
        if ($modelR->validate()&&$modelR->save()){
            OrderLog::addLog($userid,$model->id,'用户申请退款','用户申请退款：'.$order_good_id,2);
            $ordergoods->save();
            return commonApi::message('申请成功，等待商家审核');
        }
        return commonApi::message(commonApi::getModelError($model), false);
    }

    /**
     * 售后列表
     * @return array
     */
    public function actionRefundList()
    {
        $get = Yii::$app->request->get();
        $page = (int)$get['page']??1;
        $status = (int)$get['status']??0;
        $userid = self::$userid;
        $query = OrderGoods::find()
            ->select(['og.good_name','og.good_num','og.good_price','og.spec_name','og.good_info','og.refund_status','og.id as order_good_id','o.order_sn','og.total_pay_price'])
            ->alias('og')
            ->leftJoin(Order::tableName().' as o','o.id=og.order_id')
            ->where(['o.userid'=>$userid,'o.pay_status'=>1]);
        switch ($status){
            case 0:
                $query->andWhere(['og.refund_status'=>0]);
                break;
            case 1:
                $query->andWhere(['og.refund_status'=>1]);
                break;
            case 2:
                $query->andWhere(['og.refund_status'=>[2,3]]);
                break;
        }
        $data = PageApi::apiPage($query,$page);
        foreach ($data['data'] as $key=>&$datum){
            $good_info = json_decode($datum['good_info'],true);
            $datum['main_img'] = commonApi::getDomain($good_info['main_img']);
            unset($data['data'][$key]['good_info']);
        }
        return commonApi::message('成功',true,$data);
    }
}